<template>
  <div
    class="app-container flex-cloumn-box"
    v-loading="editLoading"
    element-loading-text="图片翻译中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-page-header @back="backPage" :content="form.subject"></el-page-header>

    <div v-loading="loading" class="app-container-main flex1">
      <el-form :model="form" ref="form" :rules="rules" :inline="true" label-width="150px">
        <el-row>
          <div>
            <el-col :span="24">
              <div class="title">基本信息</div>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品属性" prop="expand.productAttribute">
                <el-select v-model="form.expand.productAttribute" placeholder="商品属性">
                  <el-option
                    v-for="dict in dict.type.erp_product_attribute"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="运费模板" prop="expand.templateId">
                <el-select v-model="form.expand.templateId" placeholder="运费模板">
                  <el-option
                    v-for="dict in dict.type.erp_product_template"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value*1"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品类目" prop="categoryId">
                <el-cascader
                  filterable
                  v-model="form.categoryId"
                  :options="categoryList"
                  :props="{ value: 'id', label: 'name', emitPath: false }"
                  :show-all-levels="false"
                  clearable
                  @change="getCategoryInfo"
                >
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品单位" prop="productUnit">
                <el-select v-model="form.productUnit" placeholder="请选择商品单位" clearable size="small">
                  <el-option
                    v-for="dict in dict.type.ae_product_unit"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value*1"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="text-input" label="海关编码" prop="expand.hsCode">
                <el-input v-model="form.expand.hsCode" placeholder="海关编码" clearable></el-input>
              </el-form-item>
              <!-- <el-form-item class="text-input" label="海关编码" prop="expand.hsCode">
                <el-select
                  v-model="form.expand.hsCode"
                  filterable
                  :filter-method="dataFilter"
                  placeholder="请输入关键词"
                  clearable
                >
                  <el-option
                    v-for="item in hsCodeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <span class="span">（输入关键字搜索）</span>
              </el-form-item> -->
            </el-col>
            <el-col :span="24">
              <el-form-item label="品牌选择" prop="brandId">
                <el-select v-model="form.expand.brandId" placeholder="品牌选择" clearable>
                  <el-option
                    v-for="dict in brandList"
                    :key="dict.value"
                    :label="dict.lable"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="flexbox" label="采集链接" prop="collectUrl">
                <div class="border-box" style="padding: 0 15px; height: 100%;">
                  <a v-if="!isAdd" :href="form.collectUrl" target="_blank">{{ form.collectUrl }}</a>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="flexbox" label="商品标签" prop="classifyLabel">
                <div class="border-box">
                  <el-checkbox-group v-model="classifyValue">
                    <el-checkbox
                      v-for="(item, index) in classifyList"
                      :label="item.value"
                      :key="index">{{ item.lable }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品主图" prop="imageURLs">
                <image-upload
                  ref="uploadImage"
                  key="file-upload-image"
                  v-model="form.imageURLs"
                  @picture-edit="imageURLsEditFn"
                  isEdit
                  :fileSize="3"
                  atlasType="0"
                  isLimitsize
                  isShowSize
                  :isShowImgFormat="true"
                  isShowRecommend
                  :isShowrecommendScale="true"
                  :limit="6"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="白底图" prop="white">
                <el-button type="text" size="mini" @click="openChooseImage('1')">生成白底图</el-button>
                <image-upload
                  ref="uploadWhite"
                  key="file-upload-white"
                  v-model="form.white"
                  @picture-edit="whiteEditFn(form.white)"
                  isEdit
                  :fileSize="3"
                  atlasType="3"
                  :limit="1"
                  isShowSize
                  isShowRecommend
                  isLimitsize/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="营销图" prop="marketing">
                <el-button type="text" size="mini" @click="openChooseImage('0')">生成营销图</el-button>
                <image-upload
                  ref="uploadMarketing"
                  key="file-upload-marketing"
                  v-model="form.marketing"
                  @picture-edit="marketEditFn(form.marketing)"
                  isEdit
                  :fileSize="3"
                  atlasType="2"
                  recommendSize="750*1000"
                  :limit="1"
                  isShowSize
                  isShowRecommend
                  isLimitsize/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品视频" prop="media">
                <file-upload
                  ref="uploadVideo"
                  key="file-upload-video"
                  :fileType="['mp4']"
                  v-model="form.media"
                  :limit="1"/>
              </el-form-item>
            </el-col>
            <el-col v-if="Array.isArray(form.customAttributes)" :span="24">
              <el-form-item class="flexbox" label="产品属性" prop="">
                <div class="border-box">
                  <el-form-item
                    v-for="(item, index) in form.customAttributes"
                    :key="index"
                    class="flexbox"
                    :label="item.zhName"
                    label-width="240px"
                    :prop="attributeProp(index)"
                    :rules="customRules(item)"
                  >
                    <div class="box-input-item-class">
                      <el-input
                        v-if="item.attributeShowTypeValue == 'input'"
                        v-model.trim="item.attr_value"
                        placeholder="请输入"
                        clearable
                      />
                      <el-select v-if="item.attributeShowTypeValue == 'list_box'" v-model="item.attr_value_id"
                                 clearable>
                        <el-option
                          v-for="dict in item.values"
                          :key="dict.attr_value_id"
                          :label="dict.zhName"
                          :value="dict.attr_value_id"
                        />
                      </el-select>
                      <el-select v-if="item.attributeShowTypeValue == 'check_box'" multiple v-model="item.attr_value_id"
                                 clearable>
                        <el-option
                          v-for="dict in item.values"
                          :key="dict.attr_value_id"
                          :label="dict.zhName"
                          :value="dict.attr_value_id"
                        />
                      </el-select>
                      <span v-if="item.attr_name_id == '-1'" class="close-span"
                            @click="attributeDelete(index)">删除</span>
                    </div>
                  </el-form-item>
                  <div v-if="attributeShow" class="showBox">
                    <div class="showBox-item">
                      <el-form-item label="属性名：" prop="" label-width="80px">
                        <el-input v-model="attributeParams.attr_name" placeholder="属性名, 例如color" clearable/>
                      </el-form-item>
                    </div>
                    <div class="showBox-button">
                      <el-button type="primary" size="small" @click="attributeDefine">确定</el-button>
                      <el-button size="small" @click="attributeCancel">取消</el-button>
                    </div>
                  </div>
                  <div class="title">
                    <el-button size="mini" @click="attributeAdd">添加自定义属性</el-button>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </div>
          <div>
            <el-col :span="24">
              <div class="title">规格库存</div>
            </el-col>
            <el-col :span="24">
              <el-form-item class="flexbox" label="商品规格" prop="">
                <div class="border-box">
                  <div v-if="specificationsShow" class="showBox">
                    <div class="showBox-item">
                      <el-form-item label="规格名：" prop="" label-width="80px">
                        <el-input v-model="speInputParams.name" placeholder="规格名, 例如color"/>
                      </el-form-item>
                    </div>
                    <div class="showBox-button">
                      <el-button type="primary" size="small" @click="speDefine">确定</el-button>
                      <el-button size="small" @click="specificationsShow = false">取消</el-button>
                    </div>
                  </div>
                  <div class="title">
                    <el-button size="mini" @click="specificationsShow = !specificationsShow">添加商品规格</el-button>
                  </div>
                  <div class="tagBox">
                    <div
                      v-for="(item, index) in JSON.parse(form.expand.skuProperty || '[]')"
                      :key="item.value"
                      class="tagBox-item"
                    >
                      <div class="tagBox-item-name">
                        <span class="name-text">{{ item.name }}</span>
                        <el-button class="noneBorder" size="mini" @click="speDelete(index)">删 除</el-button>
                      </div>
                      <div class="tagBox-item-list tagBox-flex">
                        <template v-if="item.list.length > 0">
                          <div
                            class="tagBox-flex marginB"
                            v-for="(tag, tagIndex) in item.list"
                            :key="tag.value">
                            <el-input
                              size="mini"
                              v-model="editVal"
                              v-if="tag.value == editValue"
                              @keyup.enter.native="handleEditableInputConfirm(tag, index, tagIndex)"
                              @blur="handleEditableInputConfirm(tag, index, tagIndex)"
                            >
                            </el-input>
                            <el-tag
                              v-else
                              closable
                              :disable-transitions="false"
                              @click="changeValue(tag)"
                              @close="handleClose(index, tagIndex)">
                              {{ tag.name }}
                            </el-tag>
                          </div>
                        </template>
                        <el-input
                          class="input-new-tag"
                          v-if="inputParams[index].visible"
                          v-model="inputParams[index].value"
                          :ref="`saveTagInput${item.value}`"
                          size="mini"
                          @keyup.enter.native="handleInputConfirm(index)"
                          @blur="handleInputConfirm(index)"
                        >
                        </el-input>
                        <el-button v-else class="button-new-tag" :disabled="isEdit" size="mini"
                                   @click="showInput(index, item.value)">+
                          添加规格值
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <div class="paddingLeft-box">
                <el-button size="mini" @click="skuBatchSet">批量设置</el-button>
                <div class="box-flex" v-if="skuSetModel">
                  <el-form :inline="true">
                    <el-form-item
                      v-for="(item, index) in skuBatchList"
                      :key="index"
                      :label="item.name"
                    >
                      <el-select v-model="skuFormIdMap[item.value]" multiple :placeholder="`${item.name}选择`"
                                 clearable>
                        <el-option
                          v-for="dict in item.list"
                          :key="dict.value"
                          :label="dict.name"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                    <div class="width-divbox">
                      <el-form-item label="sku价格">
                        <el-input v-model="skuForm.skuPrice" clearable></el-input>
                      </el-form-item>
                      <el-form-item label="sku长度">
                        <!-- <el-input v-model="skuForm.skuLength" clearable></el-input> -->
                        <el-input-number v-model="skuForm.skuLength" :min="0" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                      <el-form-item label="sku宽度">
                        <!-- <el-input v-model="skuForm.skuWidth" clearable></el-input> -->
                        <el-input-number v-model="skuForm.skuWidth" :min="0" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                      <el-form-item label="sku高度">
                        <!-- <el-input v-model="skuForm.skuHeight" clearable></el-input> -->
                        <el-input-number v-model="skuForm.skuHeight" :min="0" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                      <el-form-item label="sku重量">
                        <!-- <el-input v-model="skuForm.skuWeight" clearable></el-input> -->
                        <el-input-number v-model="skuForm.skuWeight" :min="0" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                      <el-form-item label="sku库存">
                        <!-- <el-input v-model="skuForm.skuStock" clearable></el-input> -->
                        <el-input-number v-model="skuForm.skuStock" :min="0" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                      <el-form-item label="sku采购链接">
                        <el-input v-model="skuForm.skuBuyLink" style="width: 200px;"
                                  clearable></el-input>
                      </el-form-item>
                    </div>
                    <div>
                      <el-button size="small" type="primary" @click="skuBatchBtn(true)">确定</el-button>
                      <el-button size="small" @click="skuBatchBtn(false)">取消</el-button>
                    </div>
                  </el-form>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="paddingLeft-box marginBottom-box">
                <el-table
                  :data="newSkuList"
                  border
                  :header-cell-style="{'text-align':'center'}"
                  :cell-style="{'text-align':'center'}"
                  header-cell-class-name="table-header"
                  width="100%"
                  current-row-key="uid"
                  row-class-name="table-row">
                  <template v-if="form.expand">
                    <el-table-column
                      v-for="(leftTitle) in JSON.parse(form.expand.skuProperty || '[]')"
                      :key="leftTitle.value"
                      :label="leftTitle.name"
                      width="120"
                    >
                      <template slot-scope="scope">
                        {{ propertyLabel(scope.row.skuPropertyIds, leftTitle.value) }}
                      </template>
                    </el-table-column>
                  </template>
                  <el-table-column prop="skuImage" label="sku图片" width="90">
                    <template slot-scope="scope">
                      <el-form-item>
                        <image-upload
                          changeSize
                          :limit="1"
                          :isShowTip="false"
                          isEdit
                          isShowSize
                          v-model="scope.row.skuImage"
                          @picture-edit="skuEditFn(scope.row.skuImage, scope.$index)"
                          :fileSize="3">
                        </image-upload>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="skuCode" label="skuCode" width="120">
                    <template slot-scope="scope">
                      <el-form-item :prop="skuCodeProp(scope.$index)">
                        <el-input v-model="scope.row.skuCode"></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="skuPrice" label="sku价格" width="100">
                    <template slot-scope="scope">
                      <el-form-item :prop="skuPriceProp(scope.$index)">
                        <el-input v-model="scope.row.skuPrice"></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="skuLength" label="sku长度" width="120">
                    <template slot-scope="scope">
                      <el-form-item :prop="skuLengthProp(scope.$index)">
                        <!-- <el-input v-model="scope.row.skuLength"></el-input> -->
                        <el-input-number v-model="scope.row.skuLength" :min="1" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="skuWidth" label="sku宽度" width="120">
                    <template slot-scope="scope">
                      <el-form-item :prop="skuWidthProp(scope.$index)">
                        <!-- <el-input v-model="scope.row.skuWidth"></el-input> -->
                        <el-input-number v-model="scope.row.skuWidth" :min="1" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="skuHeight" label="sku高度" width="120">
                    <template slot-scope="scope">
                      <el-form-item :prop="skuHeightProp(scope.$index)">
                        <!-- <el-input v-model="scope.row.skuHeight"></el-input> -->
                        <el-input-number v-model="scope.row.skuHeight" :min="1" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="skuWeight" label="sku重量" width="120">
                    <template slot-scope="scope">
                      <el-form-item :prop="skuWeightProp(scope.$index)">
                        <!-- <el-input v-model="scope.row.skuWeight"></el-input> -->
                        <el-input-number v-model="scope.row.skuWeight" :min="1" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="skuStock" label="sku库存" width="120">
                    <template slot-scope="scope">
                      <el-form-item :prop="skuStockProp(scope.$index)">
                        <!-- <el-input v-model="scope.row.skuStock"></el-input> -->
                        <el-input-number v-model="scope.row.skuStock" :min="0" step-strictly controls-position="right"
                                         size="small"></el-input-number>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="skuBuyLink" label="sku采购链接">
                    <template slot-scope="scope">
                      <el-form-item :prop="skuBuyLinkProp(scope.$index)" style="width: 100%;">
                        <el-input v-model="scope.row.skuBuyLink" style="width: 100%;"></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
            <el-col :span="24">
              <el-form-item class="flexbox" label="产品属性" prop="">
                <div class="border-box">
                  <el-form-item class="text-input" label-width="80px" label="发货期" prop="expand.deliveryTime">
                    <el-input-number v-model="form.expand.deliveryTime" step-strictly :controls="false"
                                     :min="0"></el-input-number>
                    <span class="span">天</span>
                  </el-form-item>
                  <el-form-item class="text-input" label-width="80px" label="物流重量" prop="grossWeight">
                    <div>
                      <!-- <el-input v-model="form.grossWeight" placeholder="" clearable style="width: 50%;" /><span class="span">克/件</span> -->
                      <el-input-number v-model="form.grossWeight" :min="1" controls-position="right"
                                       size="small"></el-input-number>
                      <span class="span">克/件</span>
                    </div>
                  </el-form-item>
                  <div class="check-box-title">
                    <el-checkbox v-model="form.expand.isPackSell" true-label="1" false-label="0">自定义计重
                    </el-checkbox>
                  </div>
                  <div class="check-box" v-if="form.expand.isPackSell === '1'">
                    <div>
                      <span class="span">买家购买</span>
                      <el-input v-model="form.expand.baseUnit" placeholder="" clearable style="width: 70px;"/>
                      <span class="span">件以内，按单件产品重量计算运费。</span>
                    </div>
                    <div>
                      <span class="span">在此基础上，买家每多买</span>
                      <el-input v-model="form.expand.addUnit" placeholder="" clearable style="width: 70px;"/>
                      <span class="span">件，重量增加</span>
                      <el-input v-model="form.expand.addWeight" placeholder="" clearable style="width: 70px;"/>
                      <span class="span">kg</span>
                    </div>
                  </div>
                  <el-form-item class="text-input" label-width="80px" label="包装长度" prop="packageLength">
                    <!-- <el-input v-model="form.packageLength" placeholder="" clearable style="width: 50%;" /><span class="span">cm</span> -->
                    <el-input-number v-model="form.packageLength" :min="1" step-strictly controls-position="right"
                                     size="small"></el-input-number>
                    <span class="span">cm</span>
                  </el-form-item>
                  <el-form-item class="text-input" label-width="80px" label="包装宽度" prop="packageWidth">
                    <!-- <el-input v-model="form.packageWidth" placeholder="" clearable style="width: 50%;" /><span class="span">cm</span> -->
                    <el-input-number v-model="form.packageWidth" :min="1" step-strictly controls-position="right"
                                     size="small"></el-input-number>
                    <span class="span">cm</span>
                  </el-form-item>
                  <el-form-item class="text-input" label-width="80px" label="包装高度" prop="packageHeight">
                    <!-- <el-input v-model="form.packageHeight" placeholder="" clearable style="width: 50%;" /><span class="span">cm</span> -->
                    <el-input-number v-model="form.packageHeight" :min="1" step-strictly controls-position="right"
                                     size="small"></el-input-number>
                    <span class="span">cm</span>
                  </el-form-item>
                </div>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="24">
              <el-form-item class="flexbox" label="运费试算" prop="absoluteQuoteType">
                <div class="border-box">
                  <div class="item-flex-box-radio" v-if="form.expand">
                    <el-radio v-model="form.expand.absoluteQuoteType" :label="0">手动定价</el-radio>
                    <el-radio v-model="form.expand.absoluteQuoteType" :label="1">智能定价</el-radio>
                  </div>
                </div>
              </el-form-item>
            </el-col> -->
          </div>
          <div>
            <el-col :span="24">
              <div class="title">商品详情</div>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品名称" prop="subject">
                <el-input v-model="form.subject" type="textarea" placeholder="请输入商品名称"
                          :autosize="{ minRows: 2, maxRows: 4}" maxlength="128" show-word-limit clearable
                          style="width: 700px;"/>
                <el-button @click="translateBtn(1)" :loading="translateLoading1" style="margin-left: 10px;">一键翻译
                </el-button>
                <el-button @click="createTitleBtn" :loading="createTitleLoading" style="margin-left: 10px;">
                  根据标题生成新的标题
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="flexbox" label="名称关键词" prop="keyword">
                <div class="border-box">
                  <div class="tagBox">
                    <div class="tagBox-item-list">
                      <el-tag
                        :key="tag"
                        v-for="tag in keywordList"
                        closable
                        :disable-transitions="false"
                        @close="keywordClose(tag)">
                        {{ tag }}
                      </el-tag>
                      <el-input
                        class="input-new-tag"
                        v-if="inputkeywordVisible"
                        v-model="inputkeywordValue"
                        ref="keywordTagInput"
                        size="small"
                        @keyup.enter.native="keywordInputConfirm"
                        @blur="keywordInputConfirm"
                      >
                      </el-input>
                      <el-button v-else class="button-new-tag" size="mini" :disabled="titlekeywordLoading"
                                 @click="showkeywordInput">+ 添 加
                      </el-button>
                      <el-button class="button-new-tag" size="mini" :loading="titlekeywordLoading"
                                 :disabled="titlekeywordLoading" @click="grabKeywordBtn">自动抓取
                      </el-button>
                      <el-button class="button-new-tag" size="mini" :disabled="titlekeywordLoading"
                                 @click="grabEmpty(1)">一键清空
                      </el-button>
                      <el-button class="button-new-tag" size="mini" :loading="translateLoading2"
                                 @click="translateBtn(2)">一键翻译
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品详情" prop="detail">
                <el-input v-model="form.detail" type="textarea" :autosize="{ minRows: 2, maxRows: 12}"
                          style="width: 840px;" placeholder="请输入商品详情" clearable/>
                <el-button @click="translateBtn(3)" :loading="translateLoading3" style="margin-left: 10px;">一键翻译
                </el-button>
                <el-button @click="createProductDescriptionBtn" :loading="createProductLoading"
                           style="margin-left: 10px;">根据详情关键词生成详情
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="flexbox" label="详情关键词" prop="detailKeyword">
                <div class="border-box">
                  <div class="tagBox">
                    <div class="tagBox-item-list">
                      <el-tag
                        :key="tag"
                        v-for="tag in detailskeywordList"
                        closable
                        :disable-transitions="false"
                        @close="detailsKeywordClose(tag)">
                        {{ tag }}
                      </el-tag>
                      <el-input
                        class="input-new-tag"
                        v-if="inputDetailsKeywordVisible"
                        v-model="inputDetailsKeywordValue"
                        ref="detailsKeywordTagInput"
                        size="small"
                        @keyup.enter.native="detailsKeywordInputConfirm"
                        @blur="detailsKeywordInputConfirm"
                      >
                      </el-input>
                      <el-button v-else class="button-new-tag" size="mini" :disabled="detailkeywordLoading"
                                 @click="showdetailsKeywordInput">+ 添 加
                      </el-button>
                      <el-button class="button-new-tag" :loading="detailkeywordLoading" :disabled="detailkeywordLoading"
                                 size="mini" @click="grabDetailKeywordBtn">自动抓取
                      </el-button>
                      <el-button class="button-new-tag" size="mini" :disabled="detailkeywordLoading"
                                 @click="grabEmpty(2)">一键清空
                      </el-button>
                      <el-button class="button-new-tag" size="mini" :loading="translateLoading4"
                                 @click="translateBtn(4)">一键翻译
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="flexbox" label="商品详情图" prop="detailImg">
                <div class="border-box" style="width: 840px;">
                  <image-upload
                    ref="uploadDetailsImage"
                    key="file-upload-detailsimage"
                    v-model="form.detailImg"
                    @picture-edit="detailImgEdit"
                    :fileSize="3"
                    isEdit
                    isShowSize
                    :isShowImgFormat="true"
                    :isShowTip="false"
                    :limit="99"/>
                </div>
              </el-form-item>
            </el-col>
          </div>
        </el-row>
      </el-form>
      <el-backtop target='.flex1'></el-backtop>
    </div>

    <div class="flex-button">
      <el-button :loading="buttonLoading" @click="stagingBtn">暂 存
      </el-button>
      <el-button :loading="revisebuttonLoading" :disabled="disabledbuttonLoading" type="primary"
                 @click="reviseBtn">确认已完成
      </el-button>
    </div>
    <!-- 图片优化 -->
    <el-dialog :visible.sync="isPictureEdit" title="图片优化" width="1500px" append-to-body destroy-on-close>
      <PictureEditor ref="pictureRef" :key="new Date().getTime()" :data="pictureData" :onCompleted="onCompleted"/>
    </el-dialog>
    <!--  选择商品主图  -->
    <chooseImgUrl v-if="isOpenChooseImgModal" :imgType="imgType" :imageList="form.imageURLs"
                  @close="closeChooseImgModal"></chooseImgUrl>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import FileUpload from '@/components/FileUpload'
import {
  getCollectProduct,
  addCollectProductSkuProValue,
  addcollectProductSkuProperty,
  addCollectProduct,
  updateCollectProduct,
  categoryInfo,
  extractDescription,
  extractKeyWords,
  stagingCollectProduct,
  translate,
  createTitle,
  createProductDescription
} from "@/api/persongather/collectProduct";
import {getArea, getBrand, getSelect, getHsCode} from "@/api/attribute"
import {selectlistCollectProductCategory} from "@/api/gather/collectProductCategory";
import uuid from '@/utils/uuid'
import PictureEditor from '@/components/PictureEditor';
import {pictureEditor} from '@/api/picture/picture';
import {bucketUpload} from "@/utils/alioss";
import {dataURLtoFile} from "@/utils/dataURLtoFile";
import store from '@/store'
import chooseImgUrl from "@/views/gather/details/chooseImgUrl.vue";
import {queryCategoryId} from "@/api/autoOperation/python";

export default {
  components: {
    ImageUpload,
    FileUpload,
    PictureEditor,
    chooseImgUrl
  },
  dicts: ['sys_normal_disable', 'ae_product_unit', 'erp_collect_product_status', 'erp_product_attribute', 'erp_product_template'],
  data() {
    return {
      stagingTimer: "",
      form: {
        expand: {
          'brandId': null,
          'isPackSell': '0',
          'deliveryTime': null,
          'skuProperty': '[]',
          'absoluteQuoteType': null,
          'hsCode': null
        }
      },
      // sku列表批量设置表单
      skuForm: {
        skuPrice: null,
        skuLength: null,
        skuWidth: null,
        skuHeight: null,
        skuWeight: null,
        skuStock: null,
        skuBuyLink: null
      },
      skuFormIdList: [],
      skuFormIdMap: {},
      skuSetModel: false,
      // 遮罩层
      loading: true,
      // 按钮loading
      buttonLoading: false,
      revisebuttonLoading: false,
      disabledbuttonLoading: false,
      // 搜索框加载
      selectLoading: false,
      // 控制商品规格
      specificationsShow: false,
      // 表单校验
      rules: {
        "expand.productAttribute": [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        "expand.templateId": [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        // "expand.isAneroidMarkup": [
        //   { required: true, message: "必填项不能为空", trigger: "blur" }
        // ],
        // "expand.isOnlyBattery": [
        //   { required: true, message: "必填项不能为空", trigger: "blur" }
        // ],
        // "expand.isContainsBattery": [
        //   { required: true, message: "必填项不能为空", trigger: "blur" }
        // ],
        productAttribute: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        categoryId: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        productUnit: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        "expand.hsCode": [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        "expand.deliveryTime": [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        imageURLs: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        white: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        marketing: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        packageLength: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        packageWidth: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        packageHeight: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        grossWeight: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        subject: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ],
        detailImg: [
          {required: true, message: "必填项不能为空", trigger: "blur"}
        ]
      },
      // 属性值input
      inputParams: [],
      // 规格值input
      speInputParams: {
        name: ''
      },
      // 选中的标签
      classifyValue: [],
      // 全部标签列表
      classifyList: [],
      // 是否为新增
      isAdd: this.$route.params.goodsId === 'add' ? true : false,
      // 关键词
      keywordList: [],
      inputkeywordVisible: false,
      inputkeywordValue: '',
      // 详情关键词
      detailskeywordList: [],
      inputDetailsKeywordVisible: false,
      inputDetailsKeywordValue: '',
      // 品牌列表
      brandList: [],
      // 海关编码列表
      hsCodeList: [],
      hsCodeOptions: [],
      // 类目列表
      categoryList: [],
      // 类目获取的属性值
      categoryAttributeList: [],
      attributeShow: false,
      attributeParams: {
        attr_name: ''
      },
      titlekeywordLoading: false,
      detailkeywordLoading: false,
      // 翻译
      translateLoading1: false,
      translateLoading2: false,
      translateLoading3: false,
      translateLoading4: false,
      createProductLoading: false,
      createTitleLoading: false,
      editValue: null,
      isEdit: false,
      editVal: null,
      isEditVal: false,
      isPictureEdit: false,
      pictureData: {},
      isEditIndex: 0,
      editType: '',
      editLoading: false,
      isOpenChooseImgModal: false,//是否打开选择商品主图模态框
      imgType: '',//图片类型，区分白底图和营销图
    }
  },
  computed: {
    // 属性验证
    customRules() {
      return item => {
        return [
          {
            required: item.required == '1',
            validator: (rules, value, callback) => {
              let val = value
              if (item.required != '1') return callback()
              if (item.attributeShowTypeValue == 'input') val = item.attr_value
              else if (item.attributeShowTypeValue == 'list_box') val = item.attr_value_id
              else if (item.attributeShowTypeValue == 'check_box') val = item.attr_value_id
              if (Array.isArray(val)) {
                if (val.length > 0) callback()
                else callback(new Error('必填项不能为空'))
              } else {
                if (val) callback()
                else callback(new Error('必填项不能为空'))
              }
            },
            trigger: ['list_box', 'check_box'].includes(item.attributeShowTypeValue) ? 'change' : 'blur'
          }
        ]
      }
    },
    // skucode prop
    skuCodeProp() {
      return index => {
        return `skuList[${index}].skuCode`
      }
    },
    // sku价格prop
    skuPriceProp() {
      return index => {
        return `skuList[${index}].skuPrice`
      }
    },
    // sku长度prop
    skuLengthProp() {
      return index => {
        return `skuList[${index}].skuLength`
      }
    },
    // sku宽度prop
    skuWidthProp() {
      return index => {
        return `skuList[${index}].skuWidth`
      }
    },
    // sku高度prop
    skuHeightProp() {
      return index => {
        return `skuList[${index}].skuHeight`
      }
    },
    // sku重量prop
    skuWeightProp() {
      return index => {
        return `skuList[${index}].skuWeight`
      }
    },
    // sku库存prop
    skuStockProp() {
      return index => {
        return `skuList[${index}].skuStock`
      }
    },
    // sku采购链接prop
    skuBuyLinkProp() {
      return index => {
        return `skuList[${index}].skuBuyLink`
      }
    },
    // 属性prop
    attributeProp() {
      return index => {
        return `customAttributes[${index}].attr_value`
      }
    },
    // sku商品
    propertyLabel() {
      if (this.form.expand) {
        const ls = JSON.parse(this.form.expand.skuProperty || '[]')
        return (ids, val) => {
          try {
            const items = ids
              .split(';').filter(item => !!item && new RegExp(`^${val}:[0-9]+`).test(item))
              .map(it => {
                const [p1, p2] = it.split(':').filter(item => !!item)
                return ls.filter(item => item.value == p1)[0].list.filter(item => item.value == p2)[0]
              })
            return items[0].name
          } catch (e) {
            return '-'
          }
        }
      } else return '-'
    },
    // sku列表数据
    newSkuList() {
      if (this.form.expand) {
        const skuProperty = JSON.parse(this.form.expand.skuProperty || '[]')
        const idsArr = []
        skuProperty.forEach((p1, p1Index) => {
          (p1.list || []).forEach((p2, p2Index) => {
            if (!idsArr[p1Index]) idsArr.push([])
            idsArr[p1Index].push(`${p1.value}:${p2.value}`)
          })
        })
        const skuPropertyIdsArr = skuPropertyPackage(idsArr, 0)
        const list = skuPropertyIdsArr.map(ids => {
          const rowData = this.getRowData(ids)
          return rowData
        })
        this.rulesUpdate(list)
        // 长宽高重量比较大小
        const lengthArr = []
        const widthArr = []
        const heightArr = []
        const weightArr = []
        list.forEach(item => {
          if (item.skuLength) lengthArr.push(item.skuLength)
          if (item.skuWidth) widthArr.push(item.skuWidth)
          if (item.skuHeight) heightArr.push(item.skuHeight)
          if (item.skuWeight) weightArr.push(item.skuWeight)
        })
        if (lengthArr.length > 0) {
          const lengthMax = Math.max(...lengthArr)
          this.$set(this.form, 'packageLength', lengthMax)
        }
        if (widthArr.length > 0) {
          const widthMax = Math.max(...widthArr)
          this.$set(this.form, 'packageWidth', widthMax)
        }
        if (heightArr.length > 0) {
          const heightMax = Math.max(...heightArr)
          this.$set(this.form, 'packageHeight', heightMax)
        }
        if (weightArr.length > 0) {
          const weightMax = Math.max(...weightArr)
          this.$set(this.form, 'grossWeight', weightMax)
        }
        return list
      } else return []
    },
    // sku批量规格列表数据
    skuBatchList() {
      const skuProperty = JSON.parse(this.form.expand.skuProperty || '[]')
      skuProperty.forEach((item, index) => {
        skuProperty[index].list = [...skuProperty[index].list]
      })
      return [...skuProperty]
    }
  },
  methods: {
    // 打开选择商品主图模态框
    openChooseImage(e) {
      this.imgType = e
      this.isOpenChooseImgModal = true
    },
    // 关闭选择商品主图弹窗
    closeChooseImgModal(e) {
      console.log('eee', e)
      let url = this.$store.getters.domain + e
      this.isOpenChooseImgModal = false
      if (e == 'isClose') {
      } else {
        if (this.imgType == '0') {
          this.form.marketing = url
        } else {
          this.form.white = url
        }
      }
    },
    // 返回上一页
    backPage() {
      clearInterval(this.stagingTimer)
      this.$router.back()
    },
    // sku批量设置
    skuBatchSet() {
      this.skuForm = {
        skuPrice: null,
        skuLength: null,
        skuWidth: null,
        skuHeight: null,
        skuWeight: null,
        skuStock: null,
        skuBuyLink: null
      }
      this.skuSetModel = !this.skuSetModel
    },
    // sku批量设置确定取消
    skuBatchBtn(isShow) {
      if (isShow) {
        this.newSkuList.forEach(sku => {
          let isPass = true
          for (const key in this.skuFormIdMap) {
            if (this.skuFormIdMap[key].length <= 0) continue
            const item = this.skuFormIdMap[key]
            const ls = sku.skuPropertyIds
              .split(';')
              .filter(child => item.filter(it => new RegExp(`^${key}:${it}`).test(child)).length > 0)
            if (ls.length === 0) {
              isPass = false;
              break
            }
          }
          if (isPass) {
            if (this.skuForm.skuPrice) this.$set(sku, 'skuPrice', this.skuForm.skuPrice)
            if (this.skuForm.skuLength) this.$set(sku, 'skuLength', this.skuForm.skuLength)
            if (this.skuForm.skuWidth) this.$set(sku, 'skuWidth', this.skuForm.skuWidth)
            if (this.skuForm.skuHeight) this.$set(sku, 'skuHeight', this.skuForm.skuHeight)
            if (this.skuForm.skuWeight) this.$set(sku, 'skuWeight', this.skuForm.skuWeight)
            if (this.skuForm.skuStock) this.$set(sku, 'skuStock', this.skuForm.skuStock)
            if (this.skuForm.skuBuyLink) this.$set(sku, 'skuBuyLink', this.skuForm.skuBuyLink.replace(/^\s+|\s+$/g, ''))
          }
        })
      } else {
        this.skuForm = {
          skuPrice: null,
          skuLength: null,
          skuWidth: null,
          skuHeight: null,
          skuWeight: null,
          skuStock: null,
          skuBuyLink: null
        }
        this.skuSetModel = false
      }
    },
    // sku列表校验
    rulesUpdate(list) {
      this.form.skuList = list
      list.forEach((item, index) => {
        this.rules[`skuList[${index}].skuPrice`] = [
          {required: true, message: '必填项不能为空', trigger: 'blur'}
        ]
        this.rules[`skuList[${index}].skuLength`] = [
          {required: true, message: '必填项不能为空', trigger: 'blur'}
        ]
        this.rules[`skuList[${index}].skuWidth`] = [
          {required: true, message: '必填项不能为空', trigger: 'blur'}
        ]
        this.rules[`skuList[${index}].skuHeight`] = [
          {required: true, message: '必填项不能为空', trigger: 'blur'}
        ]
        this.rules[`skuList[${index}].skuWeight`] = [
          {required: true, message: '必填项不能为空', trigger: 'blur'}
        ]
        this.rules[`skuList[${index}].skuStock`] = [
          {required: true, message: '必填项不能为空', trigger: 'blur'}
        ]
        this.rules[`skuList[${index}].skuBuyLink`] = [
          {required: true, message: '必填项不能为空', trigger: 'blur'}
        ]
      })
    },
    // sku行数据
    getRowData(ids) {
      const idsArr = ids.split(',').filter(item => !!item)
      const item = this.form.skuList.filter(item => {
        const skuPropertyIds = item.skuPropertyIds.split(';').filter(item => !!item)
        return ArrayIsSame(skuPropertyIds, idsArr)
      })[0]
      if (item) {
        item.uid = item.id
        return item
      } else {
        return {
          uid: uuid(),
          skuImage: null,
          skuPrice: null,
          skuStock: null,
          skuLength: null,
          skuHeight: null,
          skuWidth: null,
          skuWeight: null,
          skuBuyLink: null,
          skuPropertyIds: ids.toString().replace(/,/g, ';')
        }
      }
    },
    /** 查询采集商品详情 */
    getInfo(id) {
      this.loading = true;
      this.$modal.loading('正在获取商品详情，请稍后······');
      getCollectProduct(id).then(res => {
        this.form = res.data
        const categoryId = res.data.categoryId
        console.log('categoryId', categoryId)
        if (categoryId) {
          this.getCategoryInfo(categoryId);
        } else {
          this.$modal.closeLoading();
        }

        if (this.form.imageURLs) {
          var imageURLs = this.form.imageURLs.split(';');
          // 过滤掉后缀为.mp4的照片
          imageURLs = imageURLs.filter(item => item.indexOf('.mp4') == -1);
          this.form.imageURLs = imageURLs.splice(0, 6).join(";");
        }
        if (this.form.white) {
          var white = this.form.white.split(';');
          this.form.white = white.splice(0, 1).toString();
        }
        if (this.form.marketing) {
          var marketing = this.form.marketing.split(';');
          this.form.marketing = marketing.splice(0, 1).toString();
        }
        if (res.data.expand) {
          if (res.data.expand.classifyLabel) this.classifyValue = res.data.expand.classifyLabel.split(',')
          else this.classifyValue = []
          if (res.data.expand.keyword) this.keywordList = res.data.expand.keyword.split(',')
          else this.keywordList = []
          if (res.data.expand.detailKeyword) this.detailskeywordList = res.data.expand.detailKeyword.split(',')
          else this.detailskeywordList = []
          const hsCode = res.data.expand.hsCode
          if (hsCode) {
            this.getHsCodeList({id: hsCode});
          } else {
            this.getHsCodeList();
          }
        } else {
          this.form = {
            ...res.data, 'expand': {
              'brandId': null,
              'isPackSell': '0',
              'deliveryTime': null,
              'skuProperty': '[]',
              'absoluteQuoteType': null,
              'hsCode': null
            }
          }
          this.classifyValue = []
          this.keywordList = []
          this.detailskeywordList = []
        }
        const length = JSON.parse(res.data.expand && res.data.expand.skuProperty || '[]').length || 0
        for (var i = 0; i < length; i++) {
          this.inputParams.push({value: '', visible: false})
        }
        this.loading = false;
      });
    },
    // 获取类目id
    getCategoryId() {
      queryCategoryId({title: this.form.subject}).then(res => {
        console.log('获取类目id', res.data)
        // this.getCategoryInfo(res.data);
      })
    },
    // 获取商品标签的选择列表
    getSelectList() {
      this.loading = true;
      getSelect().then(res => {
        this.classifyList = res.data
        this.loading = false;
      });
    },
    // 获取区域定价国家选择列表
    getAreaList() {
      this.loading = true;
      getArea().then(res => {
        this.areaList = res.data
        this.loading = false;
      });
    },
    // 获取品牌选择列表
    getBrandList() {
      this.loading = true;
      getBrand().then(res => {
        this.brandList = res.data
        this.loading = false;
      });
    },
    // 获取海关编码选择列表
    getHsCodeList(params) {
      getHsCode(params).then(res => {
        this.hsCodeList = res.data;
      });
    },
    // 远程搜索方法
    dataFilter(val) {
      if (val) { //val存在
        this.getHsCodeList({ciqName: val});
      }
    },
    // 商品类目
    getGoodsCategory() {
      this.loading = true;
      selectlistCollectProductCategory().then(response => {
        this.categoryList = this.handleTree(response.data, "id", "parentId");
      });
      this.loading = false;
    },
    /** 转换采集商品类目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 获取商品属性
    getCategoryInfo(id) {
      categoryInfo(id).then(res => {
        var resMap = new Map();
        console.log(' res获取商品属性', res.data)
        res.data.forEach(item => {
          var attribute = {
            'attr_name_id': item.attr_name_id,
            'attr_name': item.attr_name,
            'zhName': item.zhName || item.attr_name,
            'attr_value_id': item.attr_value_id,
            'attr_value': item.attr_value,
            'values': item.values,
            'attributeShowTypeValue': item.attributeShowTypeValue,
            'required': item.required
          };
          resMap.set(item.attr_name_id, attribute);
        })
        if (this.form.customAttributes == 'null') {
          this.form.customAttributes = [];
        }
        var attrOther = [];
        if (this.form.customAttributes != null && this.form.customAttributes != undefined && this.form.customAttributes != '') {
          const customAttributes = Array.isArray(this.form.customAttributes) ? this.form.customAttributes : JSON.parse(this.form.customAttributes || '[]');
          customAttributes.forEach(item => {
            if (item.attr_name_id != 2) {
              if (item.attr_name_id == -1) {
                if (item.attr_name != '' && item.attr_name != undefined) {
                  item.zhName = item.attr_name;
                  item.attr_value_id = -1;
                  item.values = undefined;
                  item.attributeShowTypeValue = 'input';
                  item.required = '0';
                  attrOther.push(item);
                }
              } else {
                var attribute = resMap.get(item.attr_name_id);
                if (attribute == undefined) {
                  attribute = {
                    'attr_name_id': -1,
                    'attr_name': item.attr_name,
                    'zhName': item.attr_name,
                    'attr_value_id': -1,
                    'attr_value': item.attr_value,
                    'values': [],
                    'attributeShowTypeValue': 'input',
                    'required': 0
                  };
                  resMap.set(item.attr_name_id, attribute);
                } else {
                  if (item.attr_value_id != -1) {
                    // 获取是否有值
                    if (attribute.attributeShowTypeValue == 'check_box') {
                      var attr_value_id = attribute.attr_value_id;
                      if (attr_value_id == undefined) {
                        attribute.attr_value_id = [item.attr_value_id];
                      } else {
                        attribute.attr_value_id.push(item.attr_value_id);
                      }
                    } else {
                      attribute.attr_value_id = item.attr_value_id;
                      attribute.attr_value = item.attr_value;
                    }

                  }
                }
              }
            }
          });
        }
        var attr = [];
        resMap.forEach((key, val) => {
          attr.push(key);
        });
        attr.sort((a, b) => Number(b.required) - Number(a.required));
        attr = [...attr, ...attrOther];
        attr.forEach(item => {
          if (item.required == '1') {
            if (item.attributeShowTypeValue == 'input' && !item.attr_value) {
              item.attr_value = '3'
            } else if (item.attributeShowTypeValue == 'list_box' && !item.attr_value_id) {
              if (item.attr_name == "Origin") {
                item.attr_value_id = 9441741844
              } else {
                item.attr_value_id = item.values[0].attr_value_id
              }
            } else if (item.attributeShowTypeValue == "check_box") {
              if (item.attr_value_id == undefined) {
                item.attr_value_id = [item.values[0].attr_value_id]
              } else if (item.attr_value_id && item.attr_value_id.length < 1) {
                item.attr_value_id.push(item.values[0].attr_value_id)
              }
            }
          }
        })
        this.$set(this.form, 'customAttributes', attr);
      }).catch(() => {
        // this.$message.error('请重新选择类目或联系管理员！');
      }).finally(() => {
        this.$modal.closeLoading()
      })
    },
    // 删除属性值
    attributeDelete(index) {
      this.form.customAttributes.splice(index, 1);
    },
    // 添加属性值
    attributeDefine() {
      if (this.attributeParams.attr_name) {
        const item = {
          attr_name: this.attributeParams.attr_name,
          zhName: this.attributeParams.attr_name,
          attr_name_id: '-1',
          attr_value: '',
          attr_value_id: '-1',
          attributeShowTypeValue: 'input'
        }
        this.form.customAttributes.push(item);
        this.attributeParams.attr_name = "";
      } else {
        this.$modal.msgError('请填写属性名')
      }
    },
    // 打开属性值弹框
    attributeAdd() {
      if (this.attributeShow) this.attributeCancel();
      else this.attributeShow = true;
    },
    // 取消属性值弹框
    attributeCancel() {
      this.attributeParams.attr_name = "";
      this.attributeShow = false;
    },
    // 删除规格属性值
    handleClose(pIndex, index) {
      if (this.form.expand) {
        const skuProperty = JSON.parse(this.form.expand.skuProperty || '[]')
        const skuKey = `${skuProperty[pIndex].value}:${skuProperty[pIndex].list[index].value}`
        skuProperty[pIndex].list.splice(index, 1)
        this.$set(this.form.expand, 'skuProperty', JSON.stringify(skuProperty))
        const skuList = this.form.skuList.filter(item => {
          return item.skuPropertyIds.indexOf(skuKey) === -1
        })
        this.$set(this.form, 'skuList', skuList)
      }
    },
    changeValue(val) {
      this.editValue = val.value;
      this.editVal = val.name;
      this.isEdit = true;
    },
    async handleEditableInputConfirm(tag, index, tagIndex) {
      if (this.form.expand) {
        const skuProperty = JSON.parse(this.form.expand.skuProperty || '[]')
        if (this.editVal) {
          skuProperty[index].list[tagIndex].name = this.editVal;
          this.$set(this.form.expand, 'skuProperty', JSON.stringify(skuProperty));
          this.editValue = null;
          this.isEdit = false;
        } else {
          this.$modal.msgError("请填写规格值");
        }
      }
    },
    // 打开规格属性值输入框
    showInput(index, value) {
      this.inputParams[index].visible = true;
      this.$nextTick(_ => {
        this.$refs[`saveTagInput${value}`][0].$refs.input.focus();
      })
    },
    // 添加规格属性值
    async handleInputConfirm(index) {
      if (this.form.expand) {
        const skuProperty = JSON.parse(this.form.expand.skuProperty || '[]')
        if (this.inputParams[index].value) {
          await addCollectProductSkuProValue({"propertyValue": this.inputParams[index].value}).then(res => {
            skuProperty[index].list.push({
              name: res.data.propertyValue,
              value: res.data.id
            })
          })
          this.$set(this.form.expand, 'skuProperty', JSON.stringify(skuProperty))
        }
      }
      this.inputParams[index].value = ''
      this.inputParams[index].visible = false
    },
    // 规格确定
    async speDefine() {
      const skuProperty = JSON.parse(this.form.expand.skuProperty || '[]')
      if (!this.speInputParams.name) {
        this.$modal.msgError("请填写规格名");
      } else {
        await addcollectProductSkuProperty({"propertyName": this.speInputParams.name}).then(res => {
          if (res.code === 200) {
            this.inputParams.push({value: '', visible: false})
            this.$modal.msgSuccess("添加完成");
            this.speInputParams.name = ''
            skuProperty.push({
              name: res.data.propertyName,
              value: res.data.id,
              list: []
            })
          }
        })
        this.$set(this.form.expand, 'skuProperty', JSON.stringify(skuProperty))
      }
    },
    // 规格删除
    speDelete(index) {
      const skuProperty = JSON.parse(this.form.expand.skuProperty || '[]')
      skuProperty.splice(index, 1)
      this.$set(this.form.expand, 'skuProperty', JSON.stringify(skuProperty))
      this.$modal.msgSuccess("删除完成");
    },
    // 确认已完成
    reviseBtn() {
      this.$refs["form"].validate((valid, obj) => {
        if (this.form.imageURLs && this.form.imageURLs.split(';').length === 6) {
          if (valid) {
            let list = this.$refs.uploadImage.fileList;
            for (let i = 0; i < list.length; i++) {
              if (list[i].isTrue) {
                this.$modal.msgError("主图尺寸不正确");
                return false
              }
            }
            if (this.$refs.uploadWhite.isTrue) {
              this.$modal.msgError("白底图尺寸不正确");
              return false;
            } else if (this.$refs.uploadMarketing.isTrue) {
              this.$modal.msgError("营销图尺寸不正确");
              return false;
            }
            // let detailList = this.$refs.uploadDetailsImage.fileList;
            // for (let i = 0; i < detailList.length; i++) {
            //   if (detailList[i].isTrue) {
            //     this.$modal.msgError("详情图尺寸不正确");
            //     return false
            //   }
            // }
            this.revisebuttonLoading = true;
            this.disabledbuttonLoading = true;
            var attrRes = [];
            if (this.form.customAttributes != null && this.form.customAttributes != undefined && this.form.customAttributes != '') {
              try {
                this.form.customAttributes.forEach(item => {
                  var obj = {};
                  if (item.attributeShowTypeValue === 'check_box') {
                    var values = item.attr_value_id;
                    values.forEach(item1 => {
                      obj = {};
                      obj.attr_name = item.attr_name;
                      obj.attr_name_id = item.attr_name_id;
                      obj.attr_value = item.attr_value;
                      obj.attr_value_id = item1;
                      attrRes.push(obj);
                    });
                  } else {
                    obj.attr_name = item.attr_name;
                    obj.attr_name_id = item.attr_name_id;
                    obj.attr_value = item.attr_value;
                    obj.attr_value_id = item.attr_value_id;
                    attrRes.push(obj);
                  }
                })
                this.form.customAttributes = JSON.stringify(attrRes);
              } catch (e) {
                this.form.customAttributes = '';
              }
            }
            this.form.expand.classifyLabel = this.classifyValue.toString();
            this.form.expand.keyword = this.keywordList.toString();
            this.form.expand.detailKeyword = this.detailskeywordList.toString();
            let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g")
            if (reg.test(this.form.subject)) {
              this.$modal.msgError("商品名称中包含中文，请先进行翻译");
              return false;
            } else if (reg.test(this.form.keyword)) {
              this.$modal.msgError("名称关键词中包含中文，请先进行翻译");
              return false;
            } else if (reg.test(this.form.detail)) {
              this.$modal.msgError("商品详情中包含中文，请先进行翻译");
              return false;
            } else if (reg.test(this.form.detailKeyword)) {
              this.$modal.msgError("商品详情关键词中包含中文，请先进行翻译");
              return false;
            }
            if (this.isAdd) {
              addCollectProduct(this.form).then(res => {
                this.$modal.msgSuccess("新增成功");
                this.$router.push(`/persongather/pergoodsList`)
              }).finally(() => {
                clearInterval(this.stagingTimer)
                this.revisebuttonLoading = false;
                this.disabledbuttonLoading = false;
              });
            } else {
              updateCollectProduct(this.form).then(res => {
                this.$modal.msgSuccess("编辑成功");
                this.$router.push(`/persongather/pergoodsList`)
              }).finally(() => {
                clearInterval(this.stagingTimer)
                this.revisebuttonLoading = false;
                this.disabledbuttonLoading = false;
              });
            }
          } else {
            var a = [];
            for (let key in obj) {
              a.push(obj[key][0].message);
            }
            this.$message({
              message: a[0],
              type: "warning",
            });
            return false;
          }
        } else {
          this.$modal.msgError("必须上传6张主图");
        }
      })
    },
    // 暂存
    stagingBtn() {
      this.buttonLoading = true;
      this.disabledbuttonLoading = true;
      var attrRes = [];
      if (this.form.customAttributes != null && this.form.customAttributes != null && this.form.customAttributes != '') {
        try {
          const customAttributes = Array.isArray(this.form.customAttributes) ? this.form.customAttributes : JSON.parse(this.form.customAttributes || '[]');
          customAttributes.forEach(item => {
            var obj = {};
            if (item.attributeShowTypeValue === 'check_box') {
              var values = item.attr_value_id;
              values.forEach(item1 => {
                obj = {};
                obj.attr_name = item.attr_name;
                obj.attr_name_id = item.attr_name_id;
                obj.attr_value = item.attr_value;
                obj.attr_value_id = item1;
                attrRes.push(obj);
              });
            } else {
              obj.attr_name = item.attr_name;
              obj.attr_name_id = item.attr_name_id;
              obj.attr_value = item.attr_value;
              obj.attr_value_id = item.attr_value_id;
              attrRes.push(obj);
            }
          })
          this.form.customAttributes = JSON.stringify(attrRes);
        } catch (e) {
          this.form.customAttributes = '';
        }
      }
      this.form.expand.classifyLabel = this.classifyValue.toString();
      this.form.expand.keyword = this.keywordList.toString();
      this.form.expand.detailKeyword = this.detailskeywordList.toString();
      stagingCollectProduct(this.form).then(res => {
        this.$modal.msgSuccess("暂存成功");
        this.$router.push(`/gather/pergoodsList`)
        this.buttonLoading = false;
        this.disabledbuttonLoading = false;
      }).finally(() => {
        this.buttonLoading = false;
        this.disabledbuttonLoading = false;
      });
    },
    // 关键词删除
    keywordClose(tag) {
      this.keywordList.splice(this.keywordList.indexOf(tag), 1);
    },
    // 关键词输入框确认
    keywordInputConfirm() {
      let inputValue = this.inputkeywordValue;
      if (inputValue) {
        this.keywordList.push(inputValue);
      }
      this.inputkeywordVisible = false;
      this.inputkeywordValue = '';
    },
    // 关键词显示输入框
    showkeywordInput() {
      this.inputkeywordVisible = true;
      this.$nextTick(_ => {
        this.$refs.keywordTagInput.$refs.input.focus();
      });
    },
    // 详情关键词删除
    detailsKeywordClose(tag) {
      this.detailskeywordList.splice(this.detailskeywordList.indexOf(tag), 1);
    },
    // 详情关键词输入框确认
    detailsKeywordInputConfirm() {
      let inputValue = this.inputDetailsKeywordValue;
      if (inputValue) {
        this.detailskeywordList.push(inputValue);
      }
      this.inputDetailsKeywordVisible = false;
      this.inputDetailsKeywordValue = '';
    },
    // 详情关键词显示输入框
    showdetailsKeywordInput() {
      this.inputDetailsKeywordVisible = true;
      this.$nextTick(_ => {
        this.$refs.detailsKeywordTagInput.$refs.input.focus();
      });
    },
    // 名称关键词自动抓取
    async grabKeywordBtn() {
      if (this.form.subject) {
        this.titlekeywordLoading = true;
        await extractKeyWords({'words': this.form.subject}).then(res => {
          if (res.code === 200) {
            const data = res.data.split(',').filter(item => !!item);
            this.keywordList = [...this.keywordList, ...data];
            this.titlekeywordLoading = false;
            this.$modal.msgSuccess("抓取成功");
          } else {
            this.titlekeywordLoading = false;
            this.$modal.msgError("抓取失败");
          }
        }).catch(() => {
          this.titlekeywordLoading = false;
        })
      } else {
        this.$modal.msgError("请先完善标题内容");
      }
    },
    // 一键清空
    grabEmpty(state) {
      if (state == '1') {
        this.keywordList = [];
      } else {
        this.detailskeywordList = [];
      }
    },
    // 详情关键词自动抓取
    async grabDetailKeywordBtn() {
      if (this.form.detail) {
        this.detailkeywordLoading = true;
        await extractDescription({'words': this.form.detail}).then(res => {
          if (res.code === 200) {
            const data = res.data.split(',').filter(item => !!item);
            this.detailskeywordList = [...this.detailskeywordList, ...data];
            this.detailkeywordLoading = false;
            this.$modal.msgSuccess("抓取成功");
          } else {
            this.detailkeywordLoading = false;
            this.$modal.msgError("抓取失败");
          }
        }).catch(() => {
          this.detailkeywordLoading = false;
        })
      } else {
        this.$modal.msgError("请先完善详情内容");
      }
    },
    // 翻译
    translateBtn(type) {
      var strText = ''
      if (type == 1) {
        strText = this.form.subject;
      } else if (type == 2) {
        strText = this.keywordList.toString();
      } else if (type == 3) {
        strText = this.form.detail;
      } else if (type == 4) {
        strText = this.detailskeywordList.toString();
      }
      if (strText) {
        if (type == 1) {
          this.translateLoading1 = true;
        } else if (type == 2) {
          this.translateLoading2 = true;
        } else if (type == 3) {
          this.translateLoading3 = true;
        } else if (type == 4) {
          this.translateLoading4 = true;
        }
        translate({'words': strText}).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("翻译成功");
            if (type == 1) {
              this.translateLoading1 = false;
              this.form.subject = res.data;
            } else if (type == 2) {
              this.translateLoading2 = false;
              var keywordArr = res.data.split(',');
              this.keywordList = [...keywordArr];
            } else if (type == 3) {
              this.translateLoading3 = false;
              this.form.detail = res.data;
            } else if (type == 4) {
              this.translateLoading4 = false;
              var keywordArr = res.data.split(',');
              this.detailskeywordList = [...keywordArr];
            }
          } else {
            this.translateLoading1 = false;
            this.translateLoading2 = false;
            this.translateLoading3 = false;
            this.translateLoading4 = false;
            this.$modal.msgError("翻译失败");
          }
        }).catch(() => {
          this.translateLoading1 = false;
          this.translateLoading2 = false;
          this.translateLoading3 = false;
          this.translateLoading4 = false;
        })
      } else {
        this.$modal.msgError("请先编辑");
      }
    },
    // 根据标题关键词生成标题
    createTitleBtn() {
      // var keyword = this.keywordList.toString();
      var keyword = this.form.subject
      if (keyword) {
        this.createTitleLoading = true;
        createTitle({'words': keyword}).then(res => {
          if (res.code === 200) {
            this.form.subject = res.data;
            this.createTitleLoading = false;
            this.$modal.msgSuccess("生成成功");
          } else {
            this.createTitleLoading = false;
            this.$modal.msgError("生成失败");
          }
        }).catch(() => {
          this.createTitleLoading = false;
        })
      } else {
        this.$modal.msgError("请先编辑");
      }
    },
    // 根据详情关键词生成详情
    createProductDescriptionBtn() {
      var keyword = this.detailskeywordList.toString();
      if (keyword) {
        this.createProductLoading = true;
        createProductDescription({'words': keyword}).then(res => {
          if (res.code === 200) {
            this.form.detail = res.data;
            this.createProductLoading = false;
            this.$modal.msgSuccess("生成成功");
          } else {
            this.createProductLoading = false;
            this.$modal.msgError("生成失败");
          }
        }).catch(() => {
          this.createProductLoading = false;
        })
      } else {
        this.$modal.msgError("请先编辑");
      }
    },
    imageURLsEditFn(item, index) {
      this.isEditIndex = index;
      this.editType = '1';
      this.pictureEditorFn(item.url);
    },
    whiteEditFn(item) {
      if (item) {
        this.editType = '2';
        this.pictureEditorFn(item);
      } else {
        this.$modal.msgError("请先上传图片");
      }
    },
    marketEditFn(item) {
      if (item) {
        this.editType = '3';
        this.pictureEditorFn(item);
      } else {
        this.$modal.msgError("请先上传图片");
      }
    },
    skuEditFn(item, index) {
      this.isEditIndex = index;
      this.editType = '4';
      this.pictureEditorFn(item);
    },
    detailImgEdit(item, index) {
      this.isEditIndex = index;
      this.editType = '5';
      this.pictureEditorFn(item.url);
    },
    pictureEditorFn(url) {
      this.editLoading = true;
      if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) url = store.getters.domain + url
      pictureEditor({url: url}).then(res => {
        if (res.code === 200) {
          this.editLoading = false;
          this.isPictureEdit = true;
          this.pictureData = res.data;
          this.$nextTick(() => {
            this.$refs.pictureRef.init();
          })
        }
      }).catch(() => {
        this.editLoading = false;
      })
    },
    onCompleted(data) {
      const op = dataURLtoFile(data[0], uuid() + '.jpg');
      this.handleUpload(op);
    },
    // 上传
    handleUpload(op) {
      let bucketName = '' // 桶名
      let dir = `images`
      bucketUpload(
        op,
        res => {
          let temp = {
            name: res.attachment,
            url: res.aliyunAddress,
            code: res.code
          }
          if (this.editType === '1') {
            const newArr = this.form.imageURLs.split(';');
            newArr[this.isEditIndex] = temp.name
            this.form.imageURLs = newArr.join(';');
          } else if (this.editType === '2') {
            this.form.white = temp.name
          } else if (this.editType === '3') {
            this.form.marketing = temp.name
          } else if (this.editType === '4') {
            this.newSkuList[this.isEditIndex].skuImage = temp.name
          } else if (this.editType === '5') {
            const newTwoArr = this.form.detailImg.split(';');
            newTwoArr[this.isEditIndex] = temp.name
            this.form.detailImg = newTwoArr.join(';');
          }
          this.isPictureEdit = false;
        },
        err => {
        },
        bucketName,
        dir
      )
    }
  },
  created() {
    console.log('this.$route.params', this.$route.params)
    if (this.$route.params.goodsId != 'add') {
      this.getInfo(this.$route.params.goodsId)
    } else {
      this.form = {
        'expand': {
          'brandId': null,
          'isPackSell': '0',
          'deliveryTime': null,
          'skuProperty': '[]',
          'absoluteQuoteType': null,
          'hsCode': null
        }
      }
      this.classifyValue = []
      this.keywordList = []
      this.detailskeywordList = []
    }
    this.getSelectList();
    this.getBrandList();
    this.getGoodsCategory();
    // this.stagingTimer = setInterval(() => {
    //   this.stagingBtn()
    // }, 30000)
  }
}

// 相同sku比较
function ArrayIsSame(_arr1, _arr2) {
  const arr1 = [..._arr1]
  const arr2 = [..._arr2]
  // 长度比较
  if (arr1.length !== arr2.length) return false
  // 项比较
  while (arr1.length > 0) {
    if (arr2.includes(arr1[0])) {
      const index = arr2.indexOf(arr1[0])
      arr1.splice(0, 1)
      arr2.splice(index, 1)
    } else {
      return false
    }
  }
  return true
}

// 商品规格包装数据
function skuPropertyPackage(skuProperty, index = 0) {
  const ids = [];
  (skuProperty[index] || []).forEach(item => {
    const _ids = [];
    const otherIds = skuPropertyPackage(skuProperty, index + 1)
    if (otherIds.length) {
      _ids.push(...otherIds.map(child => `${item},${child}`))
    } else {
      _ids.push(item)
    }
    ids.push(..._ids)
  })
  return ids
}
</script>

<style lang="scss">
.app-container {
  .app-container-main {
    padding-top: 25px;

    label {
      font-weight: normal;
    }

    .el-col {
      div {
        background: transparent;
      }

      .vue-treeselect__menu {
        background: #ffffff;
      }
    }

    .title {
      margin: 5px 0 25px 0px;
      padding: 5px 15px;
      background-color: #f6f6f6 !important;
      line-height: 40px;
      font-size: 14px;
      font-weight: 800;
      text-align: left;
    }

    .paddingLeft-box {
      padding-left: 150px;
      width: 100%;
      margin-bottom: 22px;
    }

    .marginBottom-box {
      .el-form-item {
        margin: 32px 0 !important;

        .el-form-item__content {
          width: 100%;
        }
      }

      .el-input-number--small {
        width: 90px !important;

        .el-input__inner {
          padding: 0 40px 0 10px !important;
        }
      }
    }

    .flexbox {
      width: 100%;
      display: flex;

      .el-form-item__content {
        flex: 1;
      }
    }

    .showBox {
      .showBox-item {
        width: 100%;
        padding-bottom: 20px;
      }

      .showBox-button {
        display: flex;
        padding: 0 15px 20px;
      }
    }

    .tagBox {
      .tagBox-flex {
        display: flex;
        flex-wrap: wrap;

        .el-input {
          height: 28px;
          line-height: 28px;
          width: 120px;
          margin-right: 10px;

          .el-input__inner {
            padding: 0 12px;
          }
        }
      }

      .marginB {
        margin-bottom: 10px;
      }

      .tagBox-item {
        .tagBox-item-name {
          display: flex;
          align-items: center;

          .name-text {
            line-height: 26px;
            display: block;
          }

          .noneBorder {
            border: none;
            margin-left: 10px;
          }
        }
      }

      .el-tag {
        margin-right: 10px;
        cursor: pointer;
      }

      .button-new-tag {
        margin-right: 0px;
      }

      .input-new-tag {
        width: 90px;
        margin-right: 10px;
        vertical-align: bottom;
      }
    }

    .border-box {
      border: 1px solid #EBEEF5;
      width: 840px;
      padding: 20px;

      .title {
        margin: 0 0 10px;
      }

      .box-input-item-class {
        display: flex;
        // justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .el-input {
          width: 45%;
        }

        .el-select {
          width: 45%;

          .el-input {
            width: 100%;
          }
        }

        .close-span {
          padding-left: 10px;
          font-size: 14px;
          line-height: 36px;
          color: #999999;
          cursor: pointer;

          &:hover {
            color: #1890ff;
          }
        }
      }
    }

    .box-flex {
      padding-top: 30px;
      display: flex;
      flex-wrap: wrap;

      .width-divbox {
        .el-input--medium {
          width: 100px;
        }
      }

      .el-form-item {
        margin-bottom: 10px;
      }
    }

    .text-input {
      display: block;
      margin-bottom: 22px;

      .span {
        font-size: 12px;
        line-height: 36px;
        color: #999999;
        padding-left: 10px;
      }

      .el-checkbox {
        display: flex;
        align-items: center;

        .el-checkbox__input {
          padding: 0;
        }

        .el-checkbox__label {
          font-size: 12px;
          line-height: 36px;
          color: #999999;
          padding-left: 10px;
        }
      }
    }

    .check-box-title {
      margin-left: 80px;
      margin-bottom: 10px;
      margin-top: -10px;
    }

    .check-box {
      width: 55%;
      margin-left: 80px;
      margin-bottom: 30px;
      border: 1px solid #DCDFE6;
      padding: 10px;
      font-size: 12px;
      line-height: 36px;
      color: #999999;

      span {
        padding: 0 5px;
      }
    }

    .cell {
      .el-form-item {
        margin: 22px 0;
      }
    }
  }
}

.flex-cloumn-box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: calc(100vh - 84px);
  padding-right: 0;

  .flex1 {
    flex: 1;
    overflow-y: auto;
  }

  .flex-button {
    width: 100%;
    display: flex;
    justify-content: center;
    padding: 30px 0;
  }
}
</style>
